package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"os"
	"path"
	"shop-api/internal/server"
	"shop-api/pkg/aliyun"
)

func SendCode(c *gin.Context) {
	type SendCodeReq struct {
		Phone string `json:"phone"`
	}

	req := new(SendCodeReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		Resp(c, nil, err)
		return
	}

	if req.Phone == "" {
		Resp(c, nil, fmt.Errorf("手机号不能为空"))
		return
	}

	err := server.SendCode(req.Phone)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	Resp(c, nil, nil)
	return
}

func UploadFile(c *gin.Context) {
	usedFor, ok := c.GetPostForm("used_for")
	if !ok {
		Resp(c, nil, fmt.Errorf("需要指定文件用途"))
		return
	}

	file, err := c.FormFile("file")
	if err != nil {
		Resp(c, nil, err)
		return
	}

	ext := path.Ext(file.Filename)

	fileName := uuid.NewString() + ext
	dst := viper.GetString("server.file_save") + fileName
	// 上传文件至指定的完整文件路径
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	url, err := aliyun.PutObject(c, dst, usedFor+"/"+fileName)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	err = os.Remove(dst)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	Resp(c, url, nil)
	return
}
